package com.zzl.car.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzl.car.entity.CarOrder;
import com.zzl.car.entity.Illegal;
import com.zzl.car.entity.Notice;
import com.zzl.car.entity.User;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.mapper.CarDetailInfoMapper;
import com.zzl.car.mapper.IllegalMapper;
import com.zzl.car.util.OssUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class IllegalService {

    @Autowired
    private IllegalMapper illegalMapper;
    @Autowired
    private CarOrderService carOrderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OssUtil ossUtil;

    // 违章记录的前缀
    private String IllegalKey = "IllegalInfo-";

    /*
     * 弄个分页吧
     * 也有四个状态  未处理 审核中 审核通过 审核未通过
     *              0     1      2       3
     * */
    public PageInfo<Illegal> getIllegalByUserTelephoneAndState(String telephone, Integer state,
                                                       Integer pageNum, int pageSize){
        PageInfo<Illegal> pageInfo = null;
        List<Illegal> illegals = new ArrayList<>();
        System.out.println(state.toString());
        System.out.println(pageNum.toString());
        String pageInfoKey = "IllegalPageInfo-"+state.toString()+"-"+pageNum.toString()+"-"+telephone;
        String pageNumKey = "IllegalPageNum-"+state.toString()+"-"+pageNum.toString()+"-"+telephone;
        // 先查一下缓存中是否有
        if((redisTemplate.opsForList().size(pageNumKey))!=0){

            List<Integer> illegalId = redisTemplate.opsForList().range(pageNumKey, 0, -1);
            //获取到PageInfo对象
            pageInfo =(PageInfo<Illegal>) redisTemplate.opsForValue().get(pageInfoKey);
            //获取到Illegal对象
            for(Integer id : illegalId){
                Illegal c =(Illegal) redisTemplate.opsForValue().get(IllegalKey+id.toString());
                illegals.add(c);
            }
            pageInfo.setList(illegals);
        }else{
            // 从数据库中读取
            PageHelper.startPage(pageNum,pageSize);
            if(state==-1){
                illegals = illegalMapper.getIllegalByUserTelephone(telephone);
            }else{
                illegals = illegalMapper.getIllegalByUserTelephoneAndState(telephone,state);
            }
            // 获取到之后，将所有的违章信息依次存入缓存中
            for(int i=0;i<illegals.size();i++){
                Illegal illegal = illegals.get(i);
                redisTemplate.opsForValue().set(IllegalKey+illegal.getId(),illegal);
                // 将违章信息的id存入换成中国
                redisTemplate.opsForList().rightPush(pageNumKey,illegal.getId());
            }
            // 创建pageInfo对象
            pageInfo = new PageInfo<>(illegals);
            pageInfo.setList(null);
            // 将不含list的pageInfo对象存入缓存中
            redisTemplate.opsForValue().set(pageInfoKey,pageInfo);
            // 返回含listd额pageInfo对象
            pageInfo.setList(illegals);
        }
        return pageInfo;
    }
    /*
    * 根据id获取到违章记录
    * */
    public Illegal getIllegalById(Integer id){
        Illegal illegal = null;
         illegal =(Illegal)redisTemplate.opsForValue().get(IllegalKey + id.toString());
        if(illegal==null){
            // 去数据库中查询，同时将其存入缓存
            illegal = illegalMapper.getIllegalById(id);
            redisTemplate.opsForValue().set(IllegalKey+id.toString(),illegal,2, TimeUnit.HOURS);
        }
        return illegal;
    }

    /*
    * 更改违章信息,缓存也需要更改
    * 分页信息也要更新，因为是上传凭证，0|3 -> 1
    * */
    public Illegal updateIllegal(Illegal illegal){
        Integer integer = illegalMapper.updateIllegal(illegal);
        if(integer!=1){
            throw new ZdpException(1008,"违章记录修改失败");
        }
        redisTemplate.opsForValue().set(IllegalKey+illegal.getId().toString(),illegal);
        // 删除缓存
        Set<String> keys = redisTemplate.keys("IllegalPageNum-[031]-*-"+illegal.getUserTelephone());
        redisTemplate.delete(keys);
        return illegal;
    }

    /*
    * 获取七天内的违章记录，并插入
    * */
    public Integer getIllegalAndHandler(){
        List<CarOrder> carOrders = carOrderService.getCarOderInWeek();
        for(CarOrder c : carOrders){
            rabbitTemplate.convertAndSend("getIllegal",c);
        }
        return carOrders.size();
    }

    /*
    * 提醒未处理违章的用户
    * */
    public Integer sendEmailToIllegalUser(){
        //查询到所有的未处理违章，获取到用户的电子邮箱，发送提醒邮件
        List<String> telephones = illegalMapper.getIllegalByState(0);
        //获取邮件，还要获取用户信息
        for(String telephone :telephones){
            User user = userService.getUserAllByTelephone(telephone);
            System.out.println(user);
            rabbitTemplate.convertAndSend("noticeIllegal",user);
        }
        return telephones.size();
    }

    /*
    * 用户上传凭证，状态也要变成 审核中 1
    * 返回修改后的违章记录
    * */
    public Illegal uploadIllegalEvidence(MultipartFile[] images,Integer id) throws IOException {
        // 获取到违章记录
        Illegal illegal = getIllegalById(id);
        // 获取到图片地址
        StringBuffer url = new StringBuffer();
        for(int i=0;i<images.length;i++){
            if(i==0){
                url.append(ossUtil.uploadFile(images[i],"UserEvidence"));
            }else{
                url.append(";"+ossUtil.uploadFile(images[i],"UserEvidence"));
            }
        }
        // 改变违章记录
        illegal.setEvidence(url.toString());
        // 变为审核状态
        illegal.setState(1);
        // 更新
        illegal = updateIllegal(illegal);
        return illegal;
    }

    /**
     * 获取所有违章信息
     * @param name
     * @param state
     * @param currentPage
     * @return
     */
    public PageInfo<Illegal> getAllIllegal(String name, Integer state, Integer currentPage){
        int pageAmount = 8;
        PageInfo<Illegal> pageInfo = null;
        List<Illegal> notice = new ArrayList<>();

        PageHelper.startPage(currentPage,pageAmount);
        List<Illegal> illegal = illegalMapper.getAllIllegal(name,state);

        pageInfo = new PageInfo<>(illegal);
        pageInfo.setList(illegal);

        return pageInfo;
    }

}
